<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="common/include :: header('详情页面')" />
</head>
<body>
<div class="ui-layout-center">
    <div class="col-sm-12 search-collapse">
        <form id="post-form1">
            <div class="select-list">
                <div class="col-sm-12" >
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">客户姓名：</label>
                            <label class="col-sm-6 control-label">[[${statement.customerName}]]</label>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">联系方式：</label>
                            <label class="col-sm-6 control-label">[[${statement.customerPhone}]]</label>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12" >

                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">车牌号码：</label>
                            <label class="col-sm-6 control-label">[[${statement.licensePlate}]]</label>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">汽车类型：</label>
                            <label class="col-sm-6 control-label">[[${statement.carSeries}]]</label>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12" >
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">服务类型：</label>
                            <label class="col-sm-6 control-label">[[${@dict.getLabel('si_service_catalog',statement.serviceType)}]]</label>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">到店时间：</label>
                            <label class="col-sm-6 control-label" th:text="${#dates.format(statement.actualArrivalTime, 'yyyy-MM-dd HH:mm')}"></label>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12" >
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">总消费金额：</label>
                            <label class="col-sm-6 control-label" id="totalAmount">[[${statement.totalAmount}]]</label>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">实付价格：</label>
                            <label class="col-sm-6 control-label" id="actuallyPaid">[[${statement.totalAmount-statement.discountAmount}]]</label>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12" >
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label class="col-sm-6 control-label">优惠价格：</label>
                            <input class="col-sm-6" type="number" id="discountAmount" onchange="discountFun()" name="discountAmount" th:field="${statement.discountAmount}"/>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <div class="btn-group-sm" id="myTool" role="group">
        <a class="btn btn-success" onclick="saveItem()" shiro:hasPermission="business:statement:add">
            <i class="fa fa-plus"></i> 保存
        </a>
        <a class="btn btn-info" onclick="pay()" shiro:hasPermission="business:statement:add">
            <i class="fa fa-plus"></i> 确认支付
        </a>
    </div>

    <div class="col-sm-12 select-table table-striped">
        <table id="statementItemTable"></table>
    </div>
</div>

<div class="ui-layout-east">
    <div class="col-sm-12 search-collapse">
        <form id="post-form">
            <div class="select-list">
                <ul>
                    <li>
                        <label>名称：</label>
                        <input type="text" name="name"/>
                    </li>
                    <li>
                        是否套餐：<select name="carPackage" th:with="type=${@dict.getType('si_car_package')}">
                        <option value="">所有</option>
                        <option th:each="dict : ${type}" th:text="${dict.label}" th:value="${dict.value}"></option>
                    </select>
                    </li>
                    <li>
                        服务分类：<select name="serviceCatalog" th:with="type=${@dict.getType('si_service_catalog')}">
                        <option value="">所有</option>
                        <option th:each="dict : ${type}" th:text="${dict.label}" th:value="${dict.value}"></option>
                    </select>
                    </li>
                    <li>
                        <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                    </li>
                </ul>
            </div>
        </form>
    </div>

    <div class="col-sm-12 select-table table-striped">
        <table id="bootstrap-table"></table>
    </div>
</div>
</body>
<th:block th:include="common/include :: footer" />
<th:block th:include="common/include :: layout-latest" />

<script>
    $("body").layout({
        east__size: "35%",
    });

    $(function() {
        // 获取结算单的 id
        let statementId = [[${statement.id}]];
        var options = {
            id: "statementItemTable",
            toolbar: "myTool",
            url: "/business/statementItem/query?statementId=" + statementId,    // 只查询已上架的服务单项
            uniqueId: "itemId",
            columns: [
                {
                    field: 'id',
                    title: '客户id',
                    visible: false
                },
                // 由于服务单项的 id 在结算单中是唯一的，因此将其作为 uniqueId
                {
                    field: 'itemId',
                    title: '服务单项id',
                    visible: false
                },
                {
                    field: 'itemName',
                    title: '服务项名称',
                    sortable: true
                },
                {
                    field: 'itemPrice',
                    title: '服务项价格',
                    sortable: true
                },
                {
                    field: 'itemQuantity',
                    title: '购买数量',
                    sortable: true
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-primary btn-xs" href="javascript:void(0)"' +
                            ' onclick="addItem(\'' + row.itemId + '\', this)"><i class="fa fa-plus"></i></a> ');
                        actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)"' +
                            ' onclick="decreaseItem(\'' + row.itemId + '\', this)"><i class="glyphicon glyphicon-minus"></i></a>');

                        return actions.join('');
                    }
                }]
        };
        $.table.init(options);
    });

    var prefix = ctx + "/business/serviceItem";
    $(function() {
        var options = {
            url: prefix + "/query?saleStatus=1",    // 只查询已上架的服务单项
            uniqueId: "id", // 设置唯一的 id 为服务单项的 id
            columns: [
                {
                    field: 'id',
                    title: '客户id',
                    visible: false
                },
                {
                    field: 'name',
                    title: '服务项名称',
                    sortable: true
                },
                {
                    field: 'originalPrice',
                    title: '服务项价格',
                    sortable: true
                },
                {
                    field: 'info',
                    title: '备注信息',
                    sortable: true,
                    formatter: function(value, row, index) {
                        return $.table.tooltip(value, 0, "open");
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)"' +
                            ' onclick="addItem(\'' + row.id + '\', this)"><i class="fa fa-plus"></i></a>');

                        return actions.join('');
                    }
                }]
        };
        $.table.init(options);
    });

    // 点击 + 按钮后调用的函数
    function addItem(id) {  // 这里的 id 是服务单项的 id
        // 获取当前点击的服务单项的数据
        let $bootstrap = $('#bootstrap-table');
        let $statementItemTable = $("#statementItemTable");

        // 根据服务单项 id 获取左边表格中是否有该 id 的数据
        var statementData = $statementItemTable.bootstrapTable('getRowByUniqueId', id);

        if (statementData) {
            // 如果有，则让数量加 1
            $statementItemTable.bootstrapTable('updateByUniqueId', {
                id: id,
                row: {
                    itemQuantity: statementData.itemQuantity + 1,
                }
            });
        } else {
            // 如果没有，再进行追加
            // 将数据追加到左边的表格中
            var rs = $bootstrap.bootstrapTable('getRowByUniqueId', id);
            var newData = {itemName: rs.name, itemPrice: rs.originalPrice, itemQuantity: 1, itemId: id};

            $statementItemTable.bootstrapTable('append', newData);
        }

        discountFun();
    }

    // 点击 - 按钮后执行的函数
    function decreaseItem(id) {
        let $statementItemTable = $("#statementItemTable");
        // 根据服务单项 id 获取数据
        var statementData = $statementItemTable.bootstrapTable('getRowByUniqueId', id);

        // 判断数量是否大于 1
        if (statementData.itemQuantity > 1) {
            // 让数量减少 1
            $statementItemTable.bootstrapTable('updateByUniqueId', {
                id: id,
                row: {
                    itemQuantity: statementData.itemQuantity - 1,
                }
            });
        } else {
            // 删除该条数据
            $statementItemTable.bootstrapTable('removeByUniqueId', id);
        }

        discountFun();
    }

    // 计算总金额、实付金额的函数
    function discountFun() {
        // 获取左边表格中的所有数据
        var data = $('#statementItemTable').bootstrapTable('getData',{useCurrentPage:false,includeHiddenRows:false});
        // 循环遍历数据并计算出总金额
        let totalAmount = 0;
        $.each(data, function (index, item) {
            totalAmount += item.itemQuantity * item.itemPrice;
        });

        // 获取优惠金额的数值
        let discountAmount = $("#discountAmount").val();
        // 未设置优惠金额时，给定 0
        if (!discountAmount) {
            $("#discountAmount").val(0);
            discountFun();
            return;
        }

        if (discountAmount < 0) {
            $("#discountAmount").val(0);
            discountFun();
            return;
        }

        if (totalAmount === 0) {
            $("#totalAmount").text(0);
            $("#actuallyPaid").text(0);
            return;
        }

        if (discountAmount > totalAmount) {
            $.modal.alert("优惠金额不能大于总金额！");
            $("#discountAmount").val(0);
            // 让总金额和实付金额保持一致
            /*$("#totalAmount").text(totalAmount);
            $("#actuallyPaid").text(totalAmount);*/
            discountFun();
            return;
        }
        // 计算出实付金额
        let actualPrice = totalAmount - discountAmount;
        // 将计算出的结果设置到对应的 label 中
        $("#totalAmount").text(totalAmount);
        $("#actuallyPaid").text(actualPrice);
    }

    // 点击保存按钮后执行的函数
    function saveItem() {
        $.modal.confirm("确定要保存吗？", function () {
            save();
        })
    }

    function save() {
        // 获取左边表格中的所有数据
        var data = $('#statementItemTable').bootstrapTable('getData',{useCurrentPage:false,includeHiddenRows:false});

        // 获取结算单的 id 并添加到数据中
        let statementId = [[${statement.id}]];
        $.each(data, function (index, item) {
            item.statementId = statementId;
        });

        // 将 statementId 和折扣价格放到最后一个元素上面
        data.push({statementId, itemPrice: $("#discountAmount").val()});

        // 发送 Ajax 请求
        var config = {
            url: "/business/statementItem/saveItems",
            type: 'post',
            dataType: 'json',
            contentType:"application/json",
            data: JSON.stringify(data),
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                $.operate.ajaxSuccess(result);
            }
        };

        $.ajax(config);
    }

    // 点击确认支付后执行的回调函数
    function pay(id) {
        // 获取结算单 id
        let statementId = [[${statement.id}]];
        // 弹框确认
        $.modal.confirm("确认要支付吗？", function () {
            // 支付之前先进行保存操作
            save();
            // 发送 Ajax 请求
            $.operate.get("/business/statementItem/pay?statementId=" + statementId, function () {
                $.modal.openTab("详情页面", "/business/statementItem/itemDetail?statementId=" + statementId, true);
            });
        })
    }
</script>
</html>